/**
 * Copyright 2010 Jake Jackson
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.jake.nb.ext.ant.propdisplay;

import java.io.File;
import java.io.IOException;
import java.util.List;
import javax.swing.text.BadLocationException;
import javax.swing.text.Document;
import org.jake.nb.ext.ant.parser.AntParser;
import org.openide.cookies.LineCookie;
import org.openide.filesystems.FileObject;
import org.openide.filesystems.FileUtil;
import org.openide.loaders.DataObject;
import org.openide.loaders.DataObjectNotFoundException;
import org.openide.text.Line;
import org.openide.util.Exceptions;

/**
 * Class to go to the properties file a property is defined in
 * @author JakeJ
 */
public class GotoPropertyDeclaration {

  public static void gotoDeclaration(final Document document, final int[] span) {
    String text = null;
    try {
      text = document.getText(span[0], span[1] - span[0]).replaceAll("\\$\\{", "").replaceAll("}", ""); // NOI18N
    } catch (BadLocationException ex) {
      Exceptions.printStackTrace(ex);
    }

    if (text != null) {
      final File fileForProperty = AntParser.getFileForProperty(document, text);
      if (fileForProperty != null) {
        openFile(fileForProperty, text);
      }
    }
  }

  private static void openFile(final File file, final String text) {
    final FileObject fileObject = FileUtil.toFileObject(file);
    // handle properties file in this block only
    if (fileObject != null && "text/x-properties".equals(fileObject.getMIMEType())) { // NOI18N
      int line = -1;
      try {
        final List<String> asLines = fileObject.asLines();
        String current = ""; // NOI18N
        int start = -1;
        for (int i = 0; i < asLines.size(); i++) {
          final String trimmed = asLines.get(i).trim();
          if(trimmed.length() == 0) {
            continue;
          }
          if(trimmed.endsWith("\\")) { // NOI18N
            current += trimmed.substring(0, trimmed.lastIndexOf("\\")); // NOI18N
            if(start == -1) {
              start = i;
            }
            continue;
          } else {
            if(current.length() == 0) {
              current = trimmed;
              start = i;
            } else {
              current += trimmed;
            }
          }
          if (current.startsWith(text)) {
            // found the string - get the next "="
            // remove the text and trim the string, now there should be the separator - this is not quite correct
            // but in most cases it works correctly
            // case where this will fail:
            // key\
            //   =value
            final String cleaned = current.replace(text, "").trim(); // NOI18N
            if (cleaned.startsWith("=") || cleaned.startsWith(":")) { // NOI18N
              line = start;
              break;
            }
          } else {
            current = ""; // NOI18N
            start = -1;
          }
        }
      } catch (IOException ex) {
        Exceptions.printStackTrace(ex);
      }

      if (line > -1) {
        try {
          final DataObject dataObject = DataObject.find(fileObject);
          final LineCookie lineCookie = dataObject.getLookup().lookup(LineCookie.class);
          final Line original = lineCookie.getLineSet().getOriginal(line);
          original.show(Line.ShowOpenType.OPEN, Line.ShowVisibilityType.FOCUS);
        } catch (DataObjectNotFoundException ex) {
          Exceptions.printStackTrace(ex);
        }
      }
    }
  }
}
